/**
 * User: 蕨菜
 * Date: 2019-05-15
 * Time: 11:52
 * Description: 此文件简要说明
 */

const Koa = require('koa');
const KoaStatic = require('koa-static')
const KoaBody = require('koa-bodyparser')
const Router = require('koa-router');
const cors = require('koa2-cors');
const path = require('path');
const { AppUtil } = require('./util');
const app = new Koa();
const router = new Router();

const studentRouter = require('./routes/mysql.student.route');
const teacherRouter = require('./routes/mysql.teacher.route');
const gradeRouter = require('./routes/mysql.grade.route');
const classRouter = require('./routes/mysql.class.route');

app.use(async (ctx, next) => {
    try {
        await next();
    } catch(error) {

        const errors = error.errors;
        let message = AppUtil.isEmpty(errors) ? error.message : errors[0].message;
        ctx.status = error.status || 500;
        ctx.body = {
            success: false,
            message,
            //err: error
        };
        ctx.app.emit('error', error, ctx);
    }
})
app.use(cors())
app.use(KoaBody())
app.use(async (...props) => {
    const [ctx] = props;
    let time = 0;

    if (ctx.request.url === '/performance/index1.js') {
        time = 2000;
    }
    if (ctx.request.url === '/performance/index2.js') {
        time = 5000;
    }
    if (ctx.request.url === '/performance/index.css') {
        time = 7000;
    }
    if (ctx.request.url === '/performance/dota.jpg') {
        time = 10000;
    }
    if (time !== 0) {
        await new Promise((resolve) => {
            setTimeout(() => {
                resolve()
            }, time)
        })
    }

    await KoaStatic(path.resolve(__dirname))(...props);
});
//app.use(KoaStatic(path.resolve(__dirname + '/performance')));

app.use(router.routes()).use(router.allowedMethods());
router.use('/student', studentRouter.routes(), studentRouter.allowedMethods());
router.use('/class', classRouter.routes(), classRouter.allowedMethods());
router.use('/grade', gradeRouter.routes(), gradeRouter.allowedMethods());
router.use('/teacher', teacherRouter.routes(), teacherRouter.allowedMethods());

router.get('/', async (ctx) => {
    ctx.body = 'hello world!';
})

app.listen(9999);